package com.wlgzs.booksystem.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wlgzs.booksystem.config.jwt.JWTToken;
import com.wlgzs.booksystem.config.jwt.JWTUtil;
import com.wlgzs.booksystem.entity.User;
import com.wlgzs.booksystem.mapper.UserMapper;
import com.wlgzs.booksystem.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author wlgzs-sjl
 * @date 2020/11/12 20:40
 */
public class UserRealm extends AuthorizingRealm {
    @Autowired
    UserMapper userMapper;
    @Autowired
    UserService userService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了授权");
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        //拿到当前登录的这个对象
        String username=JWTUtil.getUsername(principalCollection.toString());
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("phone",username);
        User currentUser=userService.getOne(wrapper);
        // 给该用户设置角色
        info.addRole(currentUser.getRole());
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了认证");
        String token = (String) authenticationToken.getCredentials();
        String username = JWTUtil.getUsername(token);
        if (username == null || !JWTUtil.verify(token, username)) {
            throw new AuthenticationException("token认证失败！");
        }

        //密码认证，shiro进行加密
        return new SimpleAuthenticationInfo(token,token,"UserRealm");
    }
}
